{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Preparing data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/catboost/tutorials/blob/master/hyperparameters_tuning/hyperparameters_tuning.ipynb)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "import catboost\n",
    "from catboost.datasets import titanic\n",
    "\n",
    "titanic_train, titanic_test = titanic()\n",
    "titanic_train_target = titanic_train.Survived\n",
    "\n",
    "titanic_train.drop(['PassengerId', 'Survived', 'Name', 'Parch', 'Ticket', 'Cabin', 'Embarked'], axis=1, inplace=True)\n",
    "titanic_test.drop(['PassengerId', 'Name', 'Parch', 'Ticket', 'Cabin', 'Embarked'], axis=1, inplace=True)\n",
    "\n",
    "titanic_train.head(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Simple grid search"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "titanic_model = catboost.CatBoostClassifier(\n",
    "    iterations=1000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_pool = catboost.Pool(titanic_train, titanic_train_target, cat_features=['Pclass', 'Sex', 'SibSp'])\n",
    "test_pool = catboost.Pool(titanic_test, cat_features=['Pclass', 'Sex', 'SibSp'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "grid = {\n",
    "    'learning_rate': [0.03, 0.1],\n",
    "    'depth':[4, 6, 10],\n",
    "    'l2_leaf_reg': [1, 3, 5, 7, 9]\n",
    "}\n",
    "grid_search_results = titanic_model.grid_search(grid, train_pool, shuffle=False, verbose=3, plot=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Parameters giving the best value of the loss function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "grid_search_results['params']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Available cross-validation statistics"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grid_search_results['cv_results'].keys()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Quality estimated using cross-validation:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grid_search_results['cv_results']['test-Logloss-mean'][-1]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Model is ready to use after searching:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "predicted = titanic_model.predict_proba(test_pool)\n",
    "predicted[:3]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Searching over several grids"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grid_1 = {\n",
    "    'learning_rate': [0.03, 0.1, 0.3, 0.9],\n",
    "    'bootstrap_type':['Bayesian'],\n",
    "    'bagging_temperature': [0, 1, 10]\n",
    "}\n",
    "grid_2 = {\n",
    "    'learning_rate': [0.03, 0.1, 0.3, 0.9],\n",
    "    'bootstrap_type':['Bernoulli'],\n",
    "    'subsample': [0.66, 0.7, 0.8]\n",
    "}\n",
    "grid_search_results = titanic_model.grid_search([grid_1, grid_2], train_pool, shuffle=False, verbose=4, plot=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grid_search_results['params']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Randomized search"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from scipy import stats\n",
    "\n",
    "class StrangeDistribution:\n",
    "    def __init__(self, values):\n",
    "        self.values = values\n",
    "\n",
    "    def rvs(self):\n",
    "        return self.values[0]\n",
    "\n",
    "param_distribution = {\n",
    "    'one_hot_max_size': stats.bernoulli(p=0.2, loc=2),\n",
    "    'learning_rate': StrangeDistribution([0.03, 0.1]),\n",
    "    'l2_leaf_reg': [1, 3, 5, 7, 9],\n",
    "    'depth': stats.binom(n=10, p=0.2)\n",
    "}\n",
    "\n",
    "randomized_search_results = titanic_model.randomized_search(\n",
    "    param_distribution,\n",
    "    train_pool,\n",
    "    n_iter=12,\n",
    "    shuffle=False,\n",
    "    plot=True\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "randomized_search_results['params']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# If search_by_train_test_split=False, every iteration of grid search evaluates results on cross-validation.\n",
    "randomized_search_results = titanic_model.randomized_search(\n",
    "    param_distribution,\n",
    "    train_pool,\n",
    "    n_iter=6,\n",
    "    shuffle=False,\n",
    "    search_by_train_test_split=False,\n",
    "    plot=True\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "randomized_search_results['params']"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
